from logging.handlers import RotatingFileHandler

from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from flask.ext.wtf.csrf import generate_csrf
from flask_session import Session
from flask.ext.wtf import CSRFProtect
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
from config import *


db = SQLAlchemy()
redis_store = None


def setup_log(config_name):
    """配置日志"""
    # 设置日志的记录等级
    logging.basicConfig(level=config[config_name].LOG_LEVEL)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)


def create_app(config_name):
    setup_log(config_name)
    app = Flask(__name__)
    # app添加配置
    app.config.from_object(config[config_name])
    Session(app)
    # 绑定数据库
    db.init_app(app)
    # 绑定redis数据库的地址
    global redis_store
    redis_store = redis.StrictRedis(host=ConFig.REDIS_HOST, port=ConFig.REDIS_PORT, decode_responses=True)

    # 开启CSRF防护
    CSRFProtect(app)

    # 在每次请求后就csrf_token添加到cookie
    @app.after_request
    def after_request(response):
        csrf_token = generate_csrf()
        response.set_cookie('csrf_token', csrf_token)
        return response

    from info.utils.common import user_status_monitoring
    @app.errorhandler(404)
    @user_status_monitoring
    def error_hand(e):
        user = g.user
        data={
            'user':user.to_dict() if user else None
        }
        return render_template('news/404.html',data=data)



    from info.utils.common import index_class
    app.add_template_filter(index_class, 'index_class')

    from info.modules.index import index_url
    app.register_blueprint(index_url)

    from info.modules.passport import passport_url
    app.register_blueprint(passport_url)

    from info.modules.news import news_url
    app.register_blueprint(news_url)

    from info.modules.profile import user_url
    app.register_blueprint(user_url)

    from info.modules.admin import admin_blu
    app.register_blueprint(admin_blu)



    return app
